<?php

namespace Library\Auth;

class BasicAuth extends \Library\Auth {

	private $_auth;
	private $_user;
	private $_authUser;
	private $_email = '';

	public function __construct( $auth = array() ) {
		parent::__construct();
		$this->_auth = $auth;
	}
	
	public function getBasicId() {
		return $this->_auth['basic_id'];
	}
	
	public function getCryptSalt() {
		return $this->_auth['crypt_salt'];
	}
	
	public function getEmail() {
		return $this->_email;
	}
	
	public function getUser() {
		if( $this->_user === null ) {
			if( isset( $this->_auth['user_id'] ) ) {
				$this->_user = \Bean\User::get( $this->_auth['user_id'] );
			}
		}
		return $this->_user;
	}
	
	public function getAuthUser() {
		if( $this->_authUser === null ) {
			$this->_authUser = new User( $this->getUser() );
		}
		return $this->_authUser;
	}

	public function authenticate( $data ) {
	
		$this->_email = $data['email'] = trim($data['email']);

		_c( 'Email', $data['email'] );
		_c( 'Password', $data['password'] );

		$user = _q()->get1( 'users', array( 'email' => $data['email'] ) );
		$this->_user = $user = new \Bean\Db\User( $user );
		
		$this->_auth = $auth = _q()->get1( 'auth_basics', array( 'user_id' => $user->getUserId() ) );

		if( $auth['password'] != sha1($data['password'] . $auth['crypt_salt']) ) {
			throw new \Exception( 'Invalid credentials' );
		}
		
		$this->getAuthUser()->connect();
		
		
		return $user;
	}
	
	public function check( $data ) {
	
		_c( 'Password', $data['password'] );
		_a( $data['password'] == $data['confirmation'], 'Password and confirmation does not match' );
	}

	public function create( $data ) {
	
		$salt = openssl_random_pseudo_bytes( 10 );
		
		_q()->set1( 'auth_basics', array(
			'user_id' => $data['user_id'],
			'password' => sha1($data['password'] . $salt),
			'crypt_salt' => $salt
		) );
	}

	public function change( $data ) {

		_c( 'Password', $data['new_password'] );
		
		$user = $this->authenticate( $data );

		_a( $data['new_password'] == $data['confirmation'], 'Password and confirmation does not match.' );
		
		_q()->upt( 'auth_basics', 
			array( 'password' => sha1( $data['new_password'] . $this->getCryptSalt() ) ),
			array( 'basic_id' => $this->getBasicId() ) );
	}
}

